const express = require('express');
const mysql = require('mysql2');
const app = express();
const port = 3000;
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'abc123456',
  database: 'hhh'
});// 连接数据库

app.use(express.static('public'));// 静态文件目录
app.use(express.urlencoded({ extended: false }))// 解析请求体


app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/first.html')// 发送文件

})
app.get('/register.html', (req, res) => {
    res.sendFile(__dirname + '/register.html')
})// 发送文件

app.get('/Login.html', (req, res) => {
  res.sendFile(__dirname + '/Login.html')
})

app.post('/register', (req, res) => {
    const {username,password}= req.body
    const sql = 'INSERT INTO users (username, password) VALUES (?,?)';//? 占位符 再用具体的值去替代
    connection.query(sql, [username, password], (err, results,fields) => {
      if (err) {
        console.log(err.message);
        res.sendfile(__dirname + '/register.html')// 注册失败后返回注册界面
      } else {
        res.send('Registration 成功！');
      }
    })

  });
  app.post('/login', (req, res) => {
    const usersname = req.body.username;
    const password = req.body.password;
    connection.query('SELECT * FROM users WHERE username =? AND password =?', [usersname, password], (error, results) => {
      if (error)throw error;
      if (results.length > 0) {
        res.send('登录成功');
      } else {
        res.send('登录失败');
      }
    });
  });

 





app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

